package de.openkanban.server.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import de.openkanban.server.dao.UserDao;
import de.openkanban.server.domain.User;
import de.openkanban.server.service.UserService;
import de.openkanban.shared.util.StatusCodes;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	public User signUp(User user) {
		return userDao.createUser(user);
	}

	@Override
	public boolean logIn(User user) {
		return userDao.authentificate(user);
	}

	@Override
	public StatusCodes addContact(String parentUserId, String eMail) {
		return userDao.addContact(parentUserId, eMail);
	}

	@Override
	public StatusCodes removeContact(User user, String eMail) {
		return userDao.removeContact(user, eMail);
	}

	@Override
	public User getUser(Long userId) {
		return userDao.getUser(userId);
	}

	@Override
	public User[] getContacts(Long userId) {
		return userDao.getContacts(userId);
	}

	@Override
	@Transactional
	public StatusCodes updateUser(User user) {
		User userToUpdate = userDao.getUser(user.getUserId());
		userToUpdate.setVorname(user.getVorname());
		userToUpdate.setNachname(user.getNachname());
		userToUpdate.setNamensKuerzel(user.getNamensKuerzel());
		userToUpdate.setEmail(user.getEmail());
		return userDao.updateUser(userToUpdate);
	}

	@Override
	@Transactional
	public StatusCodes updatePassword(Long userId, String oldPassword, String newPassword) {
		User user = userDao.getUser(userId);
		if (!StringUtils.isEmpty(oldPassword) && oldPassword.equals(user.getPassword())) {
			user.setPassword(newPassword);
			return userDao.updateUser(user);
		}
		return StatusCodes.INVALID_INPUT_DATA;
	}

	@Override
	public StatusCodes updateAvatar(Long userId, String avatarUrl) {
		User user = userDao.getUser(userId);
		user.setAvatarUrl(avatarUrl);
		return userDao.updateUser(user);
	}
}
